<?php
namespace Home\Controller;

use Think\Controller;

class RedController extends CommonController
{
    /**
     * 构建函数
     */
    public function __construct()
    {
        parent::__construct();

        // 领取回复
        $this->replay = [
            '您慢了一步！！',
            '红包从你嘴边悄悄溜了',
            '煮熟的红包飞了',
            '加油，再来一次',
            '你的普通发好普通',
            '你说的是哪门语言？',
        ];
    }

    /**
     * 展示
     * @return [type] [description]
     */
    public function index()
    {
        // redirect(U('red/send'));
        $this->display();
    }

    /**
     * 展示
     * @return [type] [description]
     */
    public function record()
    {
        echo 1;
        $this->display();
    }

    /**
     * 红包
     * @return [type] [description]
     */
    public function find()
    {
        $this->display();
    }

    public function info()
    {
        $id = I('post.id', 0, 'intval');

        if (!$id) {
            error(6005, '找不到该红包');
        }

        $red = M('red_bag')->alias('r')
            ->field('*')
            ->join("__USER__ u ON r.user_id = u.id")
            ->where("r.id = " . $id)
            ->find();

        if (!$red) {
            error(6006, '找不到该红包');
        }

        // 是否领取过
        $is_geted = M('red_recive_log')
            ->where(['user_id' => USER_ID, 'red_id' => $id])
            ->count();
        $red['is_geted'] = $is_geted ? 1 : 0;

        $red_log = M('red_recive_log')->alias('l')
            ->field('l.user_id,u.nickname,u.headurl,l.second,l.file_path,l.money,l.add_time')
            ->join("__RED_BAG__ r on l.red_id = r.id")
            ->join("__USER__ u ON l.user_id = u.id")
            ->where("r.id = " . $id . ' and l.is_get = 1')
            ->select();

        setting('red_share_img', 'http://sfmhb.shanfengmao.com/logo.png');
        $red_share_link = U('red/find@sfmhb.shanfengmao.com') . '?id=' . $id;

        $min_share_img_money = setting('red_share_img_min_money', 50);
        $red_share_img       = $red['image'] && $red['money'] >= $min_share_img_money ? 'http://sfmhb.shanfengmao.com' . $red['image'] : setting('red_share_img');
        $red_share_desc      = $red['content'] && $red['money'] >= $min_share_img_money ? $red['content'] : setting('red_share_desc');

        $shar_title = '土豪【' . $red['nickname'] . '】发了语音口令红包，速来领取！！！';

        $app_message = [
            'title'  => $shar_title,
            'desc'   => $red_share_desc,
            'link'   => $red_share_link,
            'imgUrl' => $red_share_img,
        ];

        $time_line = [
            'title'  => $shar_title,
            'link'   => $red_share_link,
            'imgUrl' => $red_share_img,
        ];

        success([
            'red'         => $red,
            'log'         => $red_log,
            'app_message' => $app_message,
            'time_line'   => $time_line,
        ]);
    }

    /**
     * 发红包
     * @return [type] [description]
     */
    public function send()
    {
        $this->display();
    }

    /**
     * 红包手续费信息
     * @return [type] [description]
     */
    public function commission()
    {
        setting('red_send_max_money', 6000);
        $commission = [
            'img_fee'     => setting('red_img_service_charge'),
            'service_fee' => setting('red_service_charge'),
            'max'         => setting('red_send_max_money'),
            'min'         => setting('red_send_min_money'),
        ];

        success($commission);
    }

    public function create()
    {
        $money   = I('post.money', 0.00, 'floatval');
        $title   = I('post.title', '', 'trim');
        $img     = I('post.img', '', 'trim');
        $number  = I('post.number', 0, 'intval');
        $url     = I('post.url', '', 'trim');
        $type    = I('post.type', 0, 'intval');
        $content = I('post.content', '', 'trim');

        // 红包类型，1普通 2图文
        $type = I('post.type', 1, 'intval');

        if ($money < setting('red_send_min_money')) {
            error(6001, '红包最小金额为' . setting('red_send_min_money') . '元');
        }

        if (intval($money / $number) < setting('red_single_min_money')) {
            error(6002, '单个红包最小金额为' . setting('red_single_min_money') . '元');
        }

        if ($type == 1) {
            $service_charge = round(setting('red_service_charge') * $money, 2);
        } elseif ($type == 2) {
            setting('red_img_service_charge', 0.05);
            $service_charge = round(setting('red_img_service_charge') * $money, 2);
        }

        $out_hour = setting('red_out_time');
        $out_time = date('Y-m-d H:i:s', strtotime("+$out_hour hour"));
        $red      = [
            'unique'         => $unique = generate_red_unique(USER_ID),
            'commond'        => $title,
            'user_id'        => USER_ID,
            'number'         => $number,
            'remain_number'  => $number,

            'money'          => $money,
            'remain_money'   => $money,
            'service_charge' => $service_charge,

            'type'           => $type,

            'is_pay'         => 0,
            'status'         => 1, // 新的文件存储
            'out_time'       => $out_time,
            'add_time'       => CUR_DATETIME,
        ];

        if ($type == 2) {
            $red['image']   = $img;
            $red['content'] = $content;
            $red['url']     = $url;
        }

        // 生成红包
        $red_id = M('red_bag')->add($red);

        // 生成红包订单
        $order_no = D('order', 'Service')->createRed($red_id);

        $order = M('red_order')->where(['order_no' => $order_no])->find();
        if (!$order) {
            error(6003, '创建订单失败');
        }

        if ($order['is_pay']) {
            success([
                'is_pay' => 1,
                'red_id' => $red_id,
            ]);
        } else {
            Vendor('Weixinpay.Weixinpay');

            $openid    = M('user')->where(['id' => USER_ID])->getField('openid');
            $pay_money = $order['wx_money'];
            $wxpay     = new \Weixinpay();
            $data      = $wxpay->getParameters($openid, $order_no, $pay_money, U('callback/red@sfmhb.shanfengmao.com'));

            success([
                'is_pay'            => 0,
                'red_id'            => $red_id,
                'js_api_parameters' => [
                    'appId'     => $data['appId'],
                    'nonceStr'  => $data['nonceStr'],
                    'package'   => $data['package'],
                    'paySign'   => $data['paySign'],
                    'signType'  => $data['signType'],
                    'timeStamp' => $data['timeStamp'],
                ],
            ]);
        }
    }

    public function distinguish()
    {
        $content  = I('post.content', '');
        $second   = I('post.second', 0, 'intval');
        $serverid = I('post.serverid', '');
        $red_id   = I('post.hb_id', 0, 'intval');

        $file = wx_media2local($serverid, 'amr');
        if ($file) {

            $new_file = $this->amr2wav($file);

            if ($new_file) {
                $new_file = systempath2webpath($new_file);
            } else {
                error(6014, '您并没有抢到红包');
            }

        } else {
            error(6013, '您并没有抢到红包');
        }

        $is_geted = M('red_recive_log')
            ->where(['user_id' => USER_ID, 'red_id' => $red_id])
            ->count();
        if ($is_geted) {
            error(6019, '您已经领取过了好吗');
        }

        $red = M('red_bag')->field('remain_number,remain_money,commond,out_time')->find($red_id);
        if ($red['out_time'] < CUR_DATETIME) {
            error(6015, '红包已过期');
        }

        if (!$red['remain_number']) {
            error(6016, '红包已经被领取完了');
        }

        $match_percent = $this->match($content, $red['commond']);
        $data          = [
            'red_id'        => $red_id,
            'user_id'       => USER_ID,
            'commond'       => $content,
            'second'        => $second,
            'match_percent' => $match_percent,
            'file_path'     => $new_file,
            'add_time'      => CUR_DATETIME,
        ];

        setting('red_voice_match_percent', 80.00);

        $is_get = 0;
        if ($match_percent >= setting('red_voice_match_percent')) {

            $is_get         = 1;
            $data['is_get'] = 1;
        } else {

            $is_get         = 0;
            $data['is_get'] = 0;
        }

        begin();
        if ($is_get) {

            $user_money    = round($red['remain_money'] / $red['remain_number'], 2);
            $data['money'] = $user_money;

            $result1 = D('user', 'Service')->moneyLog(USER_ID, $user_money, '领取红包');
            $result2 = M('red_bag')->where(['id' => $red_id])->setDec('remain_number');
            $result3 = M('red_bag')->where(['id' => $red_id])->setDec('remain_money', $user_money);

            // 刚好剩余一个，领取完毕
            if ($red['remain_number'] == 1) {
                $result4 = M('red_bag')->where(['id' => $red_id])->save(['status' => 3]);
            }

        }
        $id = M('red_recive_log')->add($data);

        if ($id && $is_get) {
            commit();
            $red_log = M('red_recive_log')->alias('l')
                ->field('l.user_id,u.headurl,u.nickname,l.second,l.file_path,l.money,l.add_time')
                ->join("__RED_BAG__ r on l.red_id = r.id")
                ->join("__USER__ u ON l.user_id = u.id")
                ->where("r.id = " . $red_id . ' and l.user_id = ' . USER_ID)
                ->find();
            success($red_log);
        } else {
            rollback();
            $reply = $this->replay;
            $msg   = $reply[rand(0, count($reply) - 1)];
            error(6017, $msg);
        }
    }

    /**
     * 发出的红包
     * @return [type] [description]
     */
    public function sendLog()
    {
        $where = [
            'user_id' => USER_ID,
            'status'  => ['neq', 1],
        ];

        $reds = M('red_bag')
            ->field('id,commond,remain_number,number,money,add_time')
            ->where($where)
            ->order('id desc')
            ->limit(false)
            ->select();

        $money = M('red_bag')->where($where)->sum('money');

        success([
            'reds'  => $reds,
            'count' => count($reds),
            'money' => $money,
        ]);
    }

    /**
     * 收到的红包
     * @return [type] [description]
     */
    public function receiveLog()
    {
        $where = "l.user_id = " . USER_ID . " and l.is_get = 1";

        $reds = M('red_recive_log')->alias('l')
            ->field('l.id,l.red_id,l.user_id,r.commond, l.money,l.add_time')
            ->join("__RED_BAG__ r on l.red_id = r.id")
            ->where($where)
            ->order('id desc')
            ->limit(false)
            ->select();

        $where = ['user_id' => USER_ID, 'is_get' => 1];
        $money = M('red_recive_log')->where($where)->sum('money');

        success([
            'reds'  => $reds,
            'count' => count($reds),
            'money' => $money,
        ]);
    }

    /**
     * 此方法需要安装ffmpeg 具体方法可百度或geogle
     * @return [type] [description]
     */
    private function amr2wav($file)
    {

        $new_file_name = basename($file, '.amr');

        $path    = dirname($file) . '/';
        $command = 'ffmpeg -i ' . $file . ' ' . $path . $new_file_name . '.wav';

        $result = exec($command);

        return $path . $new_file_name . '.wav';
    }

    /**
     * 中文匹配度
     * @param  [type] $needle   [description]
     * @param  [type] $haystack [description]
     * @return [type]           [description]
     */
    private function match($needle, $haystack)
    {
        if (!is_chinese($needle) || !is_chinese($haystack)) {
            return false;
        }

        $needle   = chinese2py($needle);
        $haystack = chinese2py($haystack);

        similar_text($needle, $haystack, $percent);

        return number_format($percent, 2);
    }

}
